<?php 
/*
 * Update.php for GIT
 * Version 2.0
 * by Olivier St-Laurent
 */

// Global Configurations
$fetchParentDirectory = true; // true = document_root is /public/ relative to project_root, false = document_root is same as project_root
$allowChangeBranch = true; // Allow to use ?branch=BRANCH_NAME to checkout and update from another branch
$updatDatabaseStructure = true;


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// EDIT CODE BELOW AT YOUR OWN RISK. IT MAY KILL YOUR KITTENS //////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Server-side initialisations
if ($fetchParentDirectory) {
    chdir(dirname(__DIR__));
} else {
    chdir(__DIR__);
}
$locale = 'en_CA.UTF8';
setlocale(LC_ALL, $locale);
putenv('LC_ALL='.$locale);
session_start();

// Logout
if (isset($_GET['logout'])) {
    $_SESSION['git_username'] = null;
    $_SESSION['git_password'] = null;
    header("Location: update.php".(!empty($_GET['branch']) ? '?branch='.$_GET['branch'] : ''));
    exit;
}

// Log-In
if (!empty($_POST['git_username']) && !empty($_POST['git_password'])) {
    $_SESSION['git_username'] = $_POST['git_username'];
    $_SESSION['git_password'] = $_POST['git_password'];
    header("Location: update.php".(!empty($_GET['branch']) ? '?branch='.$_GET['branch'] : ''));
    exit;
}

// Login form
if (empty($_SESSION['git_username']) || empty($_SESSION['git_password'])) {
    ?>
    <form action="update.php<?=(!empty($_GET['branch']) ? '?branch='.$_GET['branch'] : '')?>" method="post">
        <input placeholder="Your GIT Username" type="text" name="git_username" id="git_username" value=""><br />
        <input placeholder="Your GIT Password" type="password" name="git_password" value=""><br />
        <input type="submit" value="Login">
    </form>
    <script>
        document.getElementById('git_username').focus();
    </script>
    <?php
    exit;
}

echo '<pre>';


// Getting current remote origin URL
echo "Checking for valid GIT repository...\n";
exec("git remote -v", $response);
$response = implode("\n", $response);
if (strpos($response, "Not a git repository") !== false) {
    die("No GIT repository here... Please check configuration");
}
if (strlen(trim($response)) && preg_match("#\s*origin\s+(https?://)([^\s]+\.git)\s*\(fetch\)\s*#iu", $response, $matches) && !empty($matches[2])) {
    $url = $matches[1].urlencode($_SESSION['git_username']).':'.urlencode($_SESSION['git_password']).'@'.$matches[2];
    echo "FETCH URL : ".$matches[1].$matches[2]."\n\n";
} else {
    die("Error fetching remote origin URL");
}


// Fetching Current repository from Origin
echo "> ".str_replace(urlencode($_SESSION['git_password']), "********", ($cmd = 'git fetch "'.$url.'" +refs/heads/*:refs/remotes/origin/* -v'))."\n";
exec($cmd.' 2>&1', $output1, $return1);
echo implode("\n", $output1)."\n\n";
if ($return1) exit;


// Check current Branch
echo "Checking current Branch...\n";
exec("git branch", $response2);
$response2 = implode("\n", $response2);
if (strlen(trim($response2)) && preg_match("#(^|\s*)\*\s+([^\s]+)\s*#iu", $response2, $matches2)) {
    $branch = $matches2[2];
    echo "On Branch '$branch'\n\n";
} else {
    die("No branch found");
}


// Checkout another Branch
if (!empty($_GET['branch']) && $_GET['branch'] != $branch) {
    if (!$allowChangeBranch) {
        die("You are not allowed to switch branch on this server");
    }
    $branch = $_GET['branch'];
    echo "> ".($cmd = 'git checkout "'.$branch.'"')."\n";
    exec($cmd.' 2>&1', $output2, $return2);
    echo implode("\n", $output2)."\n\n";
    if ($return2) exit;
}


// GIT PULL
echo "> ".str_replace(urlencode($_SESSION['git_password']), "********", ($cmd = 'git pull "'.$url.'" +refs/heads/'.$branch.':refs/remotes/origin/'.$branch))."\n";
exec($cmd.' 2>&1', $output3, $return3);
echo implode("\n", $output3)."\n\n";
if ($return3) exit;


// Updating Database Structure
/*
if ($updatDatabaseStructure) {
    echo "> ".($cmd = 'vendor/bin/doctrine-module orm:schema:update --force')."\n";
    exec($cmd.' 2>&1', $output4, $return4);
    echo implode("\n", $output4)."\n\n";
    if ($return4 || strpos(implode("\n", $output4), "Exception]") !== false) exit;
}
*/


echo '</pre>';
?>
<h2 style="color:#0d0;">SUCCESS</h2>
